<?php

namespace App\Http\Controllers\Wap;

use App\Models\Cates;
use App\Models\Colleges;
use App\Models\Seos;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CollegeController extends Controller
{
    protected $chanel_id = 4;//设置导航选中标志

    public function __construct()
    {
        view()->share('chanel_id',$this->chanel_id);
        view()->share('seo',Seos::seo('SEO-COLLEGE'));
    }

    public function index(Request $request)
    {
        //查询类目
        $college_category = Cates::categories(1020);
        $params = [
            'catepid'  => (int)$request->get('catepid',0),
            'title'  => (string)$request->get('title',''),
            'cateid'  => (int)$request->get('cateid',0),
            'position'  => (int)$request->get('position',1),//为1，则查询所有推荐
        ];
        $fields = ['id','title','download','view','created_at','thumb','cateid'];
        $lists = Colleges::list($fields,$params,15);
        if($request->ajax()){
            return $this->writeJson(0,$lists);
        }
        $lists = json_encode($lists);
        return view('home.college.index',compact('college_category','lists'));
    }

    public function info(Request $request)
    {
        $id = (int)$request->get('id',0);
        if(empty($id)){
            return $this->writeJson(1,null,'参数错误');
        }
        $info = Colleges::select(['id','title','thumb','cateid','content','file','view','download','created_at'])
            ->where('status',Colleges::STATUS_1)
            ->with(['cate' => function ($query) {
                $query->select(['id','name']);
            }])->findOrFail($id);

        // 统计浏览量
        $info->increment('view');
        return view('home.college.info',compact('info'));
    }

    public function download(Request $request){
        $id = (int)$request->get('id',0);
        if(empty($id)) return $this->writeJson(1,null,'参数错误');
        if(auth()->guest())  return $this->writeJson(1,null,'未登录');
        $info = Colleges::findOrFail($id);
        if(empty($info['file'])) return $this->writeJson(1,null,'下载的资源不存在');
        if($info->increment('download')){
            return response()->download(public_path().'/'.strrchr($info['file'], "file"));
        };

    }

}